﻿using System;
using System.Collections.Generic;
using System.Linq;
using Castle.DynamicProxy;
using Extensions.Attribute.Cache;
using Extensions.Attribute.EventAttribute;
using MediatR;

namespace Extensions.Interceptor.Event;

public class EventIntercept:IInterceptor
{
    private readonly IMediator _mediator;

    public EventIntercept(IMediator mediator)
    {
        _mediator = mediator?? throw new ArgumentNullException(nameof(mediator));
    }
    // 这边就是同步   中间不能使用异步方法  不然会出现问题
    public  void Intercept(IInvocation invocation)
    {
        // 获取执行的方法
        var method = invocation.MethodInvocationTarget ?? invocation.Method;
        var attributes = method.GetCustomAttributes(true).OfType<EventAttribute>().ToList();
        // 如果没有 加标签  那么就直接执行方法 并且返回
        if (attributes.Count==0)
        {
            invocation.Proceed();
            return;
        }

        var timeout = TimeSpan.FromSeconds(10);
        // 前置执行的事件
        var beforeEvents = attributes.Where(p => p.EnumEventPosition == EnumEventPosition.Before)
            .OrderByDescending(p => p.Order);
        foreach (var beforeEvent in beforeEvents)
        {
             _mediator.Publish(new EventModel(beforeEvent.EventName)).Wait(timeout);
        }
        // 方法执行
        invocation.Proceed();
        // 后置执行的事件
        var afterEvents = attributes.Where(p => p.EnumEventPosition == EnumEventPosition.After)
            .OrderByDescending(p => p.Order);
        foreach (var afterEvent in afterEvents)
        {
             _mediator.Publish(new EventModel(afterEvent.EventName)).Wait(timeout);
        }
    }
}